package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-gin-admin/model"
	"github.com/go-gin-admin/util"
	"net/http"
	"time"
)

// 添加字典选项
func AddDictItem(c *gin.Context) {
	var dictItemData model.DictItem
	if err := c.BindWith(&dictItemData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	local := time.Now().Local()
	dictItemData.CreateTime = local
	dictItemData.UpdateTime = local
	insertId, err := dictItemData.InsertDictItem()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("创建错误错误"))
		return
	}
	m := make(map[string]interface{})
	m["insertId"] = insertId
	c.JSON(http.StatusOK, new(util.Response).Ok("创建成功", m))
}

// 修改字典选项
func UpdateDictItem(c *gin.Context) {
	var dictItemData model.DictItem
	if err := c.BindWith(&dictItemData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	dictItemData.UpdateTime = time.Now().Local()
	if err := dictItemData.UpdateDictItem(); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("更新失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("更新成功", nil))
}

// 删除字典选项
func RemoveDictItem(c *gin.Context) {
	var dictItemData model.DictItem
	id, _ := util.StringToInt64(c.Param("id"))
	if err := dictItemData.RemoveDictItem(id); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("删除失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("删除成功", nil))
}

// 获取所有的字典选项
func GetDictItemList(c *gin.Context) {
	// 获取参数
	pageSize, _ := util.StringToInt64(c.DefaultQuery("pageSize", "10"))
	pageIndex, _ := util.StringToInt64(c.DefaultQuery("pageIndex", "1"))
	dictId, _ := util.StringToInt64(c.Query("dictId"))
	var dictItemData model.DictItem
	data, err := dictItemData.GetDictItemList(dictId, pageIndex, pageSize)
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("获取失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("成功", data))
}

// 根据字典type获取字典选项
func GetDictItems(c *gin.Context)  {
	var dictItemData model.DictItem
	dictType := c.Query("dictType")
	dictItems, err := dictItemData.GetDictItemByType(dictType)
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("获取失败"))
		return
	}
	m := make(map[string]interface{})
	m["item"] = dictItems
	c.JSON(http.StatusOK, new(util.Response).Ok("获取成功", m))
}
